package main

import (
	"fmt"
	"net/http"
	"strconv"
)

var (
	scoreHtml = `
<!DOCTYPE html>
<html lang="zh-ch">
	<head>
		<meta charset="utf-8">
		<title>评分页面</title>
		<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
	</head>

	<body>
		<form oninput="%s" method="post" >
			<input type="text" readonly=""  name="key" style="display: none;" value="%v">
			
		%s
			
			
			<input style="height: 40px; width: 80px;" type="submit">
		</form>
	</body>
</html>
`

	tableHtml = `<table cellspacing="0" border="1" style="height: auto; width: 60%%; text-align: center;" >
          <tr align="center"  >
            <td style="font-weight: bold">%s</td>
            <td><img style="height: 100px; width: 100px;" src="%s"></img></td>
            <td>%s</td>
          <tr>
          <tr align="center"  >
            <td colspan="3">
				<input type="range" min="1" max="100" name="score_%v" value="50" style="width: 80%%;" >
				<output name="o_%v" for="score_%v">50</output></br>
				<output >评分依据</output>
				<input type="text" required name="note_%v" value="" style="width: 80%%;height: 40px;" >
            </td>
          <tr>
        </table><br>`

	errScoreAlert = `
<script type="text/javascript" charset="UTF-8">
alert("评分填写错误！");
</script>
`

	blankMsgAlert = `
<script type="text/javascript" charset="UTF-8">
alert("%s");
window.location.href="about:blank";
</script>
`
)

//

func score(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		if r.FormValue("key") != roundKey {
			w.Write([]byte(fmt.Sprintf(blankMsgAlert, "页面已过期，请从新扫码！")))
			return
		}
		t := ""
		l := ""
		for k, v := range memberList {
			t += fmt.Sprintf(
				tableHtml,
				v.Name,
				v.ImagePath,
				v.Desc,
				k, k, k, k,
			)
			l += fmt.Sprintf("o_%v.value=score_%v.value;", k, k)
		}
		str := fmt.Sprintf(scoreHtml, l, roundKey, t)
		w.Write([]byte(str))
		return
	}

	if roundKey != r.PostFormValue("key") {
		fmt.Println("key error")
		w.Write([]byte(fmt.Sprintf(blankMsgAlert, "页面已过期，请从新扫码！")))
		return
	}

	for k, v := range memberList {
		s, _ := strconv.Atoi(r.PostFormValue(fmt.Sprint("score_", k)))
		if s < scoreMin || s > scoreMax {
			w.Write([]byte(errScoreAlert))
			return
		}

		// 使用ip保存评价内容 可覆盖
		v.m[getClientIP(r)] = &data{s, r.PostFormValue(fmt.Sprint("note_", k))}
	}

	w.Write([]byte(fmt.Sprintf(blankMsgAlert, "已提交！")))
}
